#include <XEvent.h>
#include <string>
#include <vector>
#include <memory>
#include <atomic>
#include "exchangeplatform.h"
#include "exchangeserver.h"

namespace XTrade {

	class App
		: public XBoost::XBoostApp
	{
	private:
		ExchangePlatform platform_;
		ExchangeServer server_;
	public:
		App() {}

		bool start(int argc, char* argv[])
		{
			XBoostApp::init(argv[argc - 1], XBoost::XML_FLAG_JSON_FILE);
			PRINTFL("exchange=%s work_path=%s data_path_=%s"
				, name_.c_str(), work_path_.string().c_str(), data_path_.string().c_str());
			boost::property_tree::ptree & app_cfg = cfg();
			if (platform_.start(app_cfg)) {
				auto opt_server = app_cfg.get_child_optional("server");
				ASSERT(opt_server);
				return server_.start(opt_server.get());
			}
			return false;
		}

		void stop()
		{
			server_.stop();
			platform_.stop();
			term();
		}

		void run()
		{
			platform_.run();
		}
	};
}

int main(int argc, char* argv[])
{
	XTrade::App app;
	app.start(argc, argv);

	boost::asio::io_service io_service;
	//boost::asio::io_service::work work(io_service);
	std::shared_ptr<std::thread> thread_ptr = std::make_shared<std::thread>(
		//boost::bind(&boost::asio::io_service::run, &io_service)
		[&]() {
		std::cout << "start" << std::endl;
		XBoost::EvtDispatcher dispatcher(io_service);
		io_service.run();
		std::cout << "stop" << std::endl;
	}
	);
	XBoost::EvtThread evt_thread;
	evt_thread.start();
	app.run();
	evt_thread.stop();
	io_service.stop();
	thread_ptr->join();
	io_service.reset();
	thread_ptr.reset();

	app.stop();
	return 0;
}

